import { store } from '@/store';
import { usePermissionStoreHook } from '@/store/modules/permission.store';
import { useDictStoreHook } from '@/store/modules/dict.store';

import AuthAPI, { type LoginFormData } from '@/api/auth.api';
import UserAPI, { type UserInfo } from '@/api/system/user.api';

import { setAccessToken, setRefreshToken, getRefreshToken, clearToken } from '@/utils/auth';
import { Local, Session } from '@/utils/storage';
import { useTagsViewStore } from '@/store';

export const useUserStore = defineStore('user', () => {
  /**
   * 使用@vueuse/core库的 useStorage 做数据的持久化存储
   */
  // 用户信息
  const userInfo = useStorage<UserInfo>('userInfo', {} as any);

  /**
   * 登录
   *
   * @param {LoginFormData}
   * @returns
   */
  function login(LoginFormData: LoginFormData) {
    return new Promise<void>((resolve, reject) => {
      const params = {
        ...LoginFormData,
        grant_type: 'password',
        scope: 'server',
      };
      AuthAPI.login(params)
        .then((res: any) => {
          const { access_token, refresh_token } = res;
          // 存储token信息
          Session.set('token', access_token);
          Session.set('refresh_token', refresh_token);
          // setAccessToken(access_token); // eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          // setRefreshToken(refresh_token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取用户信息
   *
   * @returns {UserInfo} 用户信息
   */
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      UserAPI.getInfo()
        .then((data) => {
          if (!data) {
            reject('Verification failed, please Login again.');
            return;
          }
          console.log('userInfo-', userInfo.value);
          Object.assign(userInfo.value, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.logout()
        .then(async () => {
          // 重置所有系统状态
          await clearSessionAndCache();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 刷新 token
   */
  function refreshToken() {
    const refreshToken = Session.getRefreshToken();
    const grant_type = 'refresh_token';
    const scope = 'server';
    return new Promise<void>((resolve, reject) => {
      AuthAPI.refreshToken(refreshToken)
        .then((data) => {
          const { accessToken, refreshToken } = data;
          setAccessToken(accessToken);
          setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          console.log(' refreshToken  刷新失败', error);
          reject(error);
        });
    });
  }

  /**
   * 重置所有系统状态
   * 统一处理所有清理工作，包括用户凭证、路由、缓存等
   */
  function clearSessionAndCache() {
    return new Promise<void>((resolve) => {
      // 1. 重置用户状态
      resetUserState();

      // 2. 重置其他模块状态
      // 重置路由
      usePermissionStoreHook().resetRouter();
      // 清除字典缓存
      useDictStoreHook().clearDictCache();
      // 清除标签视图
      useTagsViewStore().delAllViews();
      console.log('clear');

      resolve();
    });
  }

  /**
   * 重置用户状态
   * 仅处理用户模块内的状态
   */
  function resetUserState() {
    // 清除用户凭证
    Session.clear();
    // 重置用户信息
    userInfo.value = {} as UserInfo;
  }

  return {
    userInfo,
    getUserInfo,
    login,
    logout,
    clearSessionAndCache,
    refreshToken,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
